<?php
	session_start();
	class ProvinciasManager{
		public static function Add($id_region, $nombre){
//			echo 'Provincias::Add: '.$nombre.'<br>';
			$db = DataBase::getInstance();

			$db->execute("INSERT INTO provincias(id_region, nombre) VALUES (".$id_region.",'".$nombre."')");
			$last_inserted_id = $db->last_inserted_id();
			return self::Get($last_inserted_id);
		}
		
		public static function Update($id, $id_region, $nombre){
			$db = DataBase::getInstance();
			$db->execute("UPDATE provincias SET id_region=".$id_region.",nombre = '".$nombre."' where id_provincia = ". $id);
		}
		
		public static function GetAll(){
			$db = DataBase::getInstance();
			$db->setQuery("select r.id_region id_region, r.nombre nombre_region, p.id_provincia id, p.nombre nombre_provincia from regiones r inner join provincias p on p.id_region = r.id_region");
			$list = $db->loadObjectList();
			return $list;
		}


		public static function GetForXmlByRegion($id){
			$db = DataBase::getInstance();
			$db->setQuery("select id_provincia id, nombre from provincias where id_region = ". $id);
			$list = $db->loadObjectList();
			return $list;
		}

		public static function GetByRegion($id){
			$db = DataBase::getInstance();
			$db->setQuery("select p.id_provincia id, p.nombre nombre from regiones r inner join provincias p on p.id_region = r.id_region where p.id_region = ". $id);
			$list = $db->loadObjectList();
			return $list;
		}

		public static function Get($id){
			$db = DataBase::getInstance();
			$db->setQuery("select r.id_region id_region, r.nombre nombre_region, p.id_provincia id, p.nombre nombre_provincia  from regiones r inner join provincias p on p.id_region = r.id_region WHERE id_provincia = ".$id);
			$list = $db->loadObjectList();
			return $list[0];
		}

		public static function Delete($id){
			$db = DataBase::getInstance();
			$db->execute("DELETE FROM provincias WHERE id_provincia= ".$id);
		}		


		public static function GetIdByName($id_region, $nombre){
			if($nombre == "" || $nombre == "x")return 'null';
			$db = DataBase::getInstance();

			$db->setQuery("SELECT id_provincia id FROM provincias WHERE nombre = '".trim($nombre)."'");
			$list = $db->loadObjectList();
			if(count($list)==0){
				$list = self::Add($id_region, trim($nombre));
			}else{
				$list = $list[0];
			}
			if($list->id != ""){
				return $list->id;
			}else
				return 'null';
		}
	}
?>